<?php
/**
 * Router.
 */
class Router extends Psa_Plugin_Router{

	function psa_main(){
		
		// global config array
		global $PSA_CFG;
		
		// web mode
		if(isset($_SERVER["REQUEST_URI"])){
			
			// remove query string from url
			$request_uri_arr = explode('?',$_SERVER["REQUEST_URI"]);
			
			// If application root folder is in subfolder from server root like: www.example.com/my/application/
			// remove unnecessary part of path. In case of url above that would be '/my/application'.
			// This value should be set in $PSA_CFG['folders']['basedir_web'] config variable in psa config.php file
			// or better in site specific config_override.php file.
			if($PSA_CFG['folders']['basedir_web'])	
				$request_uri_arr[0] = str_replace($PSA_CFG['folders']['basedir_web'] . '/','',$request_uri_arr[0]);
			else
				// remove first '/' if application is in the web server root folder
				$request_uri_arr[0] = substr($request_uri_arr[0], 1);
			
			// explode REQUEST_URI and find controller name
			$request_uri_arr = explode('/',$request_uri_arr[0]);
			
			$controller_name = 'Web_Controller';
				
			// set cookie path.
			//session_set_cookie_params(0, $PSA_CFG['folders']['basedir_web'] . '/');
				
			// start session
			session_start();
				
			// restore plugin object from session
			Psa_Plugin::get_instance()->session_restore();
		}
		// cli mode
		else if(php_sapi_name() === 'cli'){
			$controller_name = 'Cli_Controller';
			
			// load data about plugins
			Psa_Plugin::get_instance()->set_data();
			
			// change current directory 
			chdir(dirname($PSA_CFG['folders']['basedir']));
			
			$request_uri_arr = array_slice($_SERVER['argv'], 1);
		}
		else{
			// parameters for Psa_Logger::log() method
			$log_data['message']  = 'Cannot find controller.';
			$log_data['function'] = 'Router::psa_main()';
			$log_data['type']     = 'error';
			Psa_Logger::get_instance()->log($log_data);
			die();
		}
		
		// Prepare argument for psa_run_plugins() method.
		// I want to call psa_main() method of the controller and pass $request_uri_arr to the controller 
		// cause the same array will be needed there to choose models and views
		$run_plugins[$controller_name]['psa_main'] = array($request_uri_arr);
		
		// call controller.
		psa_run_plugins($run_plugins);
	}
}
